package com.integrationpath.mengine.balaur;

import javax.servlet.Servlet;

import org.eclipse.equinox.jsp.jasper.JspServlet;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.HttpService;
import org.osgi.util.tracker.ServiceTracker;

import com.integrationpath.mengine.balaur.service.impl.BalaurServiceImpl;
import com.integrationpath.mengine.console.helper.BundleEntryHttpContext;
import com.integrationpath.mengine.console.helper.ContextPathServletAdaptor;
import com.integrationpath.mengine.console.service.PluginService;

public class Activator implements BundleActivator {

	private ServiceTracker httpServiceTracker;

	public void start(BundleContext context) throws Exception {
		
		httpServiceTracker = new HttpServiceTracker(context);
		httpServiceTracker.open();
			
		PluginService service = new BalaurServiceImpl();
		// Third parameter is a hash map which allows to configure the service

		context.registerService(PluginService.class.getName(), service,	null);
		System.out.println("BalaurServiceImpl is registered");
		
	}

	public void stop(BundleContext context) throws Exception {
		httpServiceTracker.open();
	}

	private class HttpServiceTracker extends ServiceTracker {

		public HttpServiceTracker(BundleContext context) {
			super(context, HttpService.class.getName(), null);
		}

		public Object addingService(ServiceReference reference) {
			final HttpService httpService = (HttpService) context.getService(reference);
			try {
				
				HttpContext commonContext = new BundleEntryHttpContext(context.getBundle(), "/web"); //$NON-NLS-1$
				httpService.registerResources("/sidebar", "/", commonContext); //$NON-NLS-1$ //$NON-NLS-2$

				Servlet adaptedJspServlet = new ContextPathServletAdaptor(new JspServlet(context.getBundle(), "/web"), "/sidebar");  //$NON-NLS-1$//$NON-NLS-2$
				httpService.registerServlet("/sidebar/*.jsp", adaptedJspServlet, null, commonContext); //$NON-NLS-1$
				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return httpService;
		}

		public void removedService(ServiceReference reference, Object service) {
			final HttpService httpService = (HttpService) service;
			httpService.unregister("/sidebar"); //$NON-NLS-1$
			httpService.unregister("/sidebar/*.jsp"); //$NON-NLS-1$
			super.removedService(reference, service);
		}			
	}
}